﻿#include "SurfaceElectricFieldMapWindow.h"

#include <QDir>
#include <tuple>
#include <QDebug>
#include <QSplitter>
#include <QHBoxLayout>
#include <QListWidgetItem>

#include <vtkPointSet.h>
#include <vtkDataSet.h>
#include <vtkRenderer.h>
#include <vtkProperty.h>
#include <vtkTextProperty.h>
#include <vtkScalarBarActor.h>
#include <vtkUnstructuredGrid.h>
#include <QVTKOpenGLNativeWidget.h>
#include <vtkGenericOpenGLRenderWindow.h>
#include <vtkCamera.h>
#include <vtkTextActor.h>
#include <vtkLookupTable.h>

#include "FieldGraphGenerator.h"
#include "SurfaceElectricFieldMapSidebarSettings.h"
#include "SurfaceElectricFieldMapSettingDialog.h"
#include "InfomationGraph3DBasical.h"
#include "PropPickerCallbackHander.h"
#include "BaseModule/IBaseSignal.h"
#include "SurfaceElectricFieldMapSettingData.h"
#include "SurfaceElectricFieldMapSidebarData.h"
#include "AnimationSettingData.h"
#include "MutiVTKFilesReader.h"
#include "MutiVTUFilesReader.h"

#include <vtkWindowToImageFilter.h>
#include <vtkPointData.h>
#include <vtkImageData.h>
#include <vtkImageExport.h>
#include "PostMarkerInteractionStyle.h"
#include "FramelessDragableTableWidget.h"
#include <vtkCaptionActor2D.h>
#include <vtkCubeAxesActor.h>
// #include <vtkPNGWriter.h>
#include <vtkJPEGWriter.h>
#include <chrono>
#include <thread>
#include <QTimer>
#include <vtkActor.h>
#include <vtkScalarBarWidget.h>
#include <vtkCellData.h>
#include <vtkDataSet.h>
#include "DataClipperGenerator.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "DataManager/WindowTotalData.h"
#include "GeomtryActorGenerator.h"
#include "VTPFilesReader.h"
#include "DataClipperFilter.h"
#include "PipelineManager.h"
#include "MainWindowSignalHandler.h"
#include "BaseWidget/IWidgetSignal.h"
#include "AnimationTooBarInfoData.h"
#include "FieldScalarBarGenerator.h"
#include "CommonFunction.h"

namespace
{
    int decideLogCoefficients(int type)
    {
        //增益（7）人体吸收比（13）功率（16）方向性系数（17）雷达散射截面（18）
        QList<int> log10TypeList{ 7, 13, 16, 17, 18 };
        if (log10TypeList.contains(type))
        {
            return 10;
        }
        else
        {
            return 20;
        }
    }

    QString getUnit(int type)
    {
        QString unit;
        switch (type)
        {
        case 3:
            unit = "V/m";
            break;
        case 4:
            unit = "A/m";
            break;
        case 5:
        case 6:
            unit = "V";
            break;
        case 15:
            unit = "C/m^3";
            break;
        default:
            unit = "";
            break;
        }
        return unit;
    }
}

namespace pst
{
    SurfaceElectricFieldMapWindow::SurfaceElectricFieldMapWindow(QWidget* parent, int windowId)
        : Graph3DWindowBase(parent),
        m_sidebarSettings(new SurfaceElectricFieldMapSidebarSettings(this)),
        m_mainSettingDialog(new SurfaceElectricFieldMapSettingDialog(this)),
        m_windowId(windowId),
        //m_commonSetting(new SurfaceElectricFieldMapSettingData(this, m_mainSettingDataId)),
        m_isAnimationDataPrepared(false)
        //, m_geometrySettingData(new GeometrySettingData(this))
        , m_cubeAxesSettingData(new CubeAxesActorSettingData(this))
        //, m_markerDataTable(new FramelessDragableTableWidget(this))
    {
        QHBoxLayout* layout = new QHBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->setStretch(0, 1);
        layout->setStretch(1, 0);

        //QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
        layout->addWidget(this->m_qvtkWidget);
        layout->addWidget(m_sidebarSettings);
        //splitter->setSizes({ 3000, 1000 });
        //layout->addWidget(splitter);

        m_sidebarSettings->setMainWiondowId(m_windowId);
        m_mainSettingDialog->setMainWindowId(m_windowId);

        m_doubleClickCallback = vtkSmartPointer<PropPickerCallbackHander>::New();
        this->m_renderWindow3D->GetInteractor()->AddObserver(vtkCommand::LeftButtonDoubleClickEvent, m_doubleClickCallback);

        initScalarBarSettingConnection();
        initSidebarSettingConnection();

        m_markerDataTable->getInnerTableWidget()->setColumnCount(6);
        QStringList nameList{ "MarkerID", "标记名", "标记类型","场名", "坐标", "值" };
        m_markerDataTable->getInnerTableWidget()->setHorizontalHeaderLabels(nameList);
        m_markerDataTable->setGeometry(20, 20, 300, 120);
        m_markerDataTable->getInnerTableWidget()->setColumnHidden(0, true);
        m_markerDataTable->hide();

        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::signal_renameCheck, this, &SurfaceElectricFieldMapWindow::slot_renameCheck);
        connect(m_mainSettingDialog, &SurfaceElectricFieldMapSettingDialog::signal_checkResultNameIsValid, this, &SurfaceElectricFieldMapWindow::slot_checkResultNameIsValid);
        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_closeTree, this, &SurfaceElectricFieldMapWindow::slot_closeTree);
        // this->setInteractorStlyleToPicking();
        // m_pickerInteractorStyle->setPickerType(1);
        // m_pickerInteractorStyle->setEnablePicking(true);
    }

    QList<InfomationGraph3DBasical*> SurfaceElectricFieldMapWindow::getGraph3DInfoList()
    {
        return m_graphInfoList;
    }

    void SurfaceElectricFieldMapWindow::setActiveAnimation(bool active)
    {
        initAnimationInfoTextActor();
        auto widget = m_sidebarSettings->getCurveNameListWidget();
        if (m_animationType == 0) // 动数据
        {
            m_dataTimer->setInterval(1000. / m_animationSettingData->frameRate() / m_animationSpeed);

            if (!active)
            {
                m_dataTimer->stop();
                widget->setFocusPolicy(Qt::StrongFocus);
                widget->setSelectionMode(QAbstractItemView::SingleSelection);
                //m_sidebarSettings->setControlPanelEditable(true);
                m_sidebarSettings->setControlPlaneToAnimationState(false);
                connectSignalsAndSlots();
            }
            else
            {
                prepareAnimationData();
                m_dataTimer->start();
                //m_sidebarSettings->setControlPanelEditable(false);
                m_sidebarSettings->setControlPlaneToAnimationState(true);
                disconnectSignalsAndSlots();
                widget->setFocusPolicy(Qt::NoFocus);
                widget->setSelectionMode(QAbstractItemView::NoSelection);
                MainWindowSignalHandler::getInstance()->setToolButtonExportMotionGraphState(false);
                if (m_isExportingAnimation)
                {
                    emit IBaseSignalInstance->signal_UpdateStatusBarInformation(QStringLiteral("导出动图正在进行中..."), true);
                    QCoreApplication::processEvents();
                }
            }
        }

        else if (m_animationType == 1) // 动相机
        {
            if (!active)
            {
                m_cameraTimer->stop();
                //m_sidebarSettings->setControlPanelEditable(true);
                widget->setFocusPolicy(Qt::StrongFocus);
                widget->setSelectionMode(QAbstractItemView::SingleSelection);
                widget->viewport()->setFocusPolicy(Qt::StrongFocus);
                m_sidebarSettings->setControlPlaneToAnimationState(false);

                connectSignalsAndSlots();
            }
            else
            {
                m_animationCameraAngle = 0.0;
                m_animationCameraCount = 0;
                m_cameraTimer->start();

                //m_sidebarSettings->setControlPanelEditable(false);
                m_sidebarSettings->setControlPlaneToAnimationState(true);

                widget->setFocusPolicy(Qt::NoFocus);
                widget->setSelectionMode(QAbstractItemView::NoSelection);
                widget->viewport()->setFocusPolicy(Qt::NoFocus);
                disconnectSignalsAndSlots();
                MainWindowSignalHandler::getInstance()->setToolButtonExportMotionGraphState(false);
                if (m_isExportingAnimation)
                {
                    emit IBaseSignalInstance->signal_UpdateStatusBarInformation(QStringLiteral("导出动图正在进行中..."), true);
                    QCoreApplication::processEvents();
                }

            }
        }
        m_animationInfoTextActor->SetVisibility(active);
        emit IWidgetSignalInstance->signal_setShowAnimationTextWidget(active);

        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::exportAnimationData(const QString& path)
    {
        m_isExportingAnimation = true;
        m_loopCount = 0;
        m_animationImageList.clear();
        m_exportAnimationPath = path;
        m_isBeginExportAnimation = true;

        if (m_animationType == 0) // 动数据
        {
            prepareAnimationData();
            setActiveAnimation(true);

            for (auto info : m_graphInfoList)
            {
                info->m_lastFrameIndexBeforeExportAnimation = info->m_currentAnimationIndex;
            }
        }
        else if (m_animationType == 1) // 动相机
        {
            setActiveAnimation(true);
        }
    }

    void SurfaceElectricFieldMapWindow::exportSourceDataToLocal()
    {
        QHash<QString, QString> hash;
        bool isSuc = false;
        for (auto i : m_graphInfoList)
        {
            QFileInfo sourceFile(i->m_filePath);
            auto suffix = sourceFile.suffix();
            QString str;
            if (suffix == "vtk")
            {
                str = tr("vtk 文件 (*.vtk);");
            }
            else if (suffix == "vtu")
            {
                str = tr("vtu 文件 (*.vtu);");
            }
            else if (suffix == "vtp")
            {
                str = tr("vtp 文件 (*.vtp);");
            }
            else
            {
                IBaseSignalInstance->signal_sendErrorMessageToUI("不支持的文件格式");
                return;
            }

            QString desFilePath = QFileDialog::getSaveFileName(this, tr("导出数据"), "",
                str);
            if (desFilePath.isEmpty())
            {
                return;
            }

            if (!sourceFile.exists())
            {
                IBaseSignalInstance->signal_sendErrorMessageToUI("源文件不存在");
                return;
            }
            bool _isSamePath = false;
            QString _tempSourceFilePath{};
            if (i->m_filePath == desFilePath)
            {
                auto _tempfi = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
                _tempfi += "/" + sourceFile.fileName();
                isSuc = QFile::copy(i->m_filePath, _tempfi);
                // isSuc = true;
                // continue;
                _tempSourceFilePath = _tempfi;
                _isSamePath = true;
            }
            QFile desFile(desFilePath);
            if (desFile.exists())
            {
                QFile::remove(desFilePath);
            }
            if (_isSamePath)
            {
                isSuc = QFile::copy(_tempSourceFilePath, desFilePath);
                if (isSuc)
                {
                    QFile::remove(_tempSourceFilePath);
                }
            }
            else
                isSuc = QFile::copy(i->m_filePath, desFilePath);
            if (!isSuc)
            {
                IBaseSignalInstance->signal_sendErrorMessageToUI("导出数据失败");
            }
            else
                hash.insert(sourceFile.fileName(), desFilePath);
                GlobalHelperInstance->setFileTimes(desFilePath);
        }
        if (isSuc)
        {
            auto _res = IdaDialogMsg::showDialog(nullptr, QStringLiteral("导出数据成功！"), EDialogMsg::Normal, QStringLiteral("成功"), {QStringLiteral("确定")});

            if (!hash.isEmpty())
            {
                QString json = GlobalHelperInstance->hashToJsonString(hash);
                QString tmp = "\"" + json + "\"";
                QString pyCode = QString("PostProcessing.exportData(%1)").arg(tmp);
                emit IBaseSignalInstance->signal_execPYCode(QStringList{pyCode}, true, false);
            }
        }
    }

    void SurfaceElectricFieldMapWindow::pyExportSourceDataToLocal(QString filePath)
    {
        QHash<QString, QString> hash = GlobalHelperInstance->jsonStringToHash(filePath);

        for (auto i : m_graphInfoList)
        {
            QFileInfo sourceFile(i->m_filePath);
            QString srcFileName = sourceFile.fileName();
            QString desFilePath = hash[srcFileName];
            QFile::copy(i->m_filePath, desFilePath);
        }
    }

    void SurfaceElectricFieldMapWindow::addAMarkerDataToPickedDataDisplayWindow(Marker3DDataInfo* info)
    {
        int count = 0;
        auto tableWidget = m_markerDataTable->getInnerTableWidget();
        int row = tableWidget->rowCount();
        tableWidget->insertRow(row);
        tableWidget->setItem(row, count++, new QTableWidgetItem(QString::number(info->m_markerId)));
        tableWidget->setItem(row, count++, new QTableWidgetItem(info->m_markerName));
        QString markerType = info->m_markerType == 0 ? "Point" : "Cell";
        tableWidget->setItem(row, count++, new QTableWidgetItem(markerType));
        tableWidget->setItem(row, count++, new QTableWidgetItem(info->m_fieldName));
        QString markerPosition = "(" + QString::number(info->m_markerPosition[0]) + "," + QString::number(info->m_markerPosition[1]) + "," + QString::number(info->m_markerPosition[2]) + ")";
        tableWidget->setItem(row, count++, new QTableWidgetItem(markerPosition));
        tableWidget->setItem(row, count++, new QTableWidgetItem(info->m_markerValue));
        updatePickedDataDisplayWindowVisibility();
    }

    void SurfaceElectricFieldMapWindow::updateClipper(bool activeClipper)
    {
        for (auto info : m_graphInfoList)
        {
            if (info->m_fieldGraphGenerator == nullptr)
            {
                qDebug() << "SurfaceElectricFieldMapWindow::updateClipper info->m_fieldGraphGenerator == nullptr";
                return;
            }

            if (info->m_dataClipperFilter == nullptr)
            {
                info->m_dataClipperFilter = new DataClipperFilter();
                auto filterManager = info->m_fieldGraphGenerator->GetScalarPipelineManager();
                filterManager->AddFilter("Clipper", info->m_dataClipperFilter);
            }

            //if (info->m_dataClipperGenerator == nullptr)
            //{
                //info->m_dataClipperGenerator = new DataClipperGenerator(this);
                //auto color = info->m_actor->GetProperty()->GetColor();
                //info->m_dataClipperGenerator->getClipActor()->GetProperty()->SetColor(color);
            //}

            //info->m_dataClipperGenerator->setInputData(info->m_data);
            info->m_dataClipperFilter->setEnabled(activeClipper);
            info->m_dataClipperFilter->setPlaneNormalDirection(
                m_planeNormalDirection[0], m_planeNormalDirection[1], m_planeNormalDirection[2]);
            info->m_dataClipperFilter->setPlaneOrigin(
                m_planeOrigin[0], m_planeOrigin[1], m_planeOrigin[2]);
            info->m_dataClipperFilter->setInsideOut(m_planeInsideOut);
            if (info->m_valueGroupNameIndex == -1)
            {
                info->m_fieldGraphGenerator->UpdateGeometryActor();
            }
            else
            {
                info->m_fieldGraphGenerator->UpdateScalarFieldActor();
            }
            //info->m_dataClipperGenerator->setLookupTable(info->m_fieldGraphGenerator->GetScalarsLookupTable());
            //info->m_dataClipperGenerator->update();

            // auto visibility = info->m_fieldGraphGenerator->GetScalarsFieldActor()->GetVisibility();
            //m_render3D->AddActor(info->m_dataClipperGenerator->getClipActor());

            ////同步透明度和缩放
            //for (auto i : m_dataMap)
            //{
            //    if (i.first == info)
            //    {
            //        auto mainSettingData = i.second;
            //        auto resultDataSettingData = mainSettingData->getResultDataSettingData();
            //        info->m_dataClipperGenerator->getClipActor()->GetProperty()->SetOpacity(1 - resultDataSettingData->getResultDataTransparency() / 100.);
            //        info->m_dataClipperGenerator->getClipActor()->SetScale(resultDataSettingData->getResultDataScaleFactor());
            //    }
            //}

            ////生成裁剪平面的actor
            //QList<vtkActor*> actorList;
            //for (auto i : m_curveMap)
            //{
            //    if (i->m_actor->GetVisibility() || info->m_dataClipperGenerator->getClipActor()->GetVisibility())
            //    {
            //        actorList.append(i->m_actor);
            //    }
            //    if (i->m_geomtryActorGenerator != nullptr && i->m_geomtryActorGenerator->getActor()->GetVisibility())//考虑几何
            //    {
            //        actorList.append(i->m_geomtryActorGenerator->getActor());
            //    }
            //}
            //auto isSuc = this->CreateExpandedPlaneActor(actorList, m_planeNormalDirection, m_planeOrigin);
            //if (!isSuc)
            //{
            //    return;
            //}
            //m_render3D->AddActor(m_clipperPlaneActor);

            auto item = info->m_sidebarItem;
            if (item == nullptr)
            {
                return;
            }
            slot_showHideItemActor(item);
        }

        updateClipperPlaneActor();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::updateClipperPlaneActor()
    {
        //生成裁剪平面的actor
        QList<vtkDataSet*> dataList;
        for (auto i : m_graphInfoList)
        {
            if (i->m_actor->GetVisibility() /*|| info->m_dataClipperGenerator->getClipActor()->GetVisibility()*/)
            {
                dataList.append(i->m_actor->GetMapper()->GetInput());
            }
            if (i->m_geomtryActorGenerator != nullptr && i->m_geomtryActorGenerator->getActor()->GetVisibility())//考虑几何
            {
                dataList.append(i->m_geomtryActorGenerator->getGeometryPolyData());
            }
        }
        //auto isSuc = this->CreateExpandedPlaneActor(actorList, m_planeNormalDirection, m_planeOrigin);
        auto isSuc = this->CreateExpandedPlaneActor(dataList, m_planeNormalDirection, m_planeOrigin);
        if (!isSuc)
        {
            return;
        }
        m_render3D->AddActor(m_clipperPlaneActor);
    }

    void SurfaceElectricFieldMapWindow::setWindowID(int windowID)
    {
        m_windowId = windowID;
    }
    int SurfaceElectricFieldMapWindow::getWindowID() const
    {
        return m_windowId;
    }

    void SurfaceElectricFieldMapWindow::setWindowUniversalID(int windowUniversalID)
    {
        m_windowUniversalID = windowUniversalID;
    }
    int SurfaceElectricFieldMapWindow::getWindowUniversalID() const
    {
        return m_windowUniversalID;
    }

    QDomElement& SurfaceElectricFieldMapWindow::writeToProjectFile(QDomDocument* doc, QDomElement* element, bool isdiso)
    {
        QDomElement _SurfaceElectricFieldMapWindowDataRoot = doc->createElement("GraphWindow");
        QDomAttr _WindowUniversalIDattr = doc->createAttribute("WindowUniversalID");
        _WindowUniversalIDattr.setValue(QString::number(m_windowUniversalID));
        _SurfaceElectricFieldMapWindowDataRoot.setAttributeNode(_WindowUniversalIDattr);
        QDomAttr _idattr = doc->createAttribute("WindowID");
        _idattr.setValue(QString::number(m_windowId));
        _SurfaceElectricFieldMapWindowDataRoot.setAttributeNode(_idattr);
        QDomAttr typeattr = doc->createAttribute("WindowType");
        typeattr.setValue("SurfaceElectricFieldMapWindow");
        _SurfaceElectricFieldMapWindowDataRoot.setAttributeNode(typeattr);

        element->appendChild(_SurfaceElectricFieldMapWindowDataRoot);

        m_cubeAxesSettingData->writeToProjectFile(doc, &_SurfaceElectricFieldMapWindowDataRoot, true, isdiso);
        for (auto _graphDataInfo : m_graphInfoList)
        {
            _graphDataInfo->writeToProjectFile(doc, &_SurfaceElectricFieldMapWindowDataRoot, GraphType::SurfaceElectricFieldMap, isdiso);
        }
        writeToProjectFile3DWindowBase(doc, &_SurfaceElectricFieldMapWindowDataRoot);

        return _SurfaceElectricFieldMapWindowDataRoot;
    }

    void SurfaceElectricFieldMapWindow::readFromProjectFile(QDomElement* element, bool isdiso)
    {
        m_windowUniversalID = element->attribute("WindowUniversalID").toInt();
        int id = element->attribute("WindowID").toInt();
        m_windowId = id;

        auto _CubeAxesActorSettingDataFromWindowNodeList = element->elementsByTagName("CubeAxesActorSettingDataFromWindow");
        m_cubeAxesSettingData->readFromProjectFile(&_CubeAxesActorSettingDataFromWindowNodeList.at(0).toElement(), true, isdiso);

        auto _infosNodeList = element->elementsByTagName("InfomationGraph3DBasical");
        auto _infosCount = _infosNodeList.count();
        if (_infosCount == 0)
            return;
        for (int i = 0; i < _infosCount; i++)
        {
            // InfomationGraph3DBasical* info = nullptr;
            QDomElement elemModel = _infosNodeList.at(i).toElement();
            auto _ProjectTreeSourceItemID = elemModel.attribute("ProjectTreeSourceItemID").toInt();
            if (_ProjectTreeSourceItemID != -1)
            {
                // 通过info的projectTreeItem到mainwindow构造完整的info信息
                auto info = MainWindowSignalHandlerInstance->BuildCompleteGraph3DInfoByProjectTreeItem(_ProjectTreeSourceItemID, GraphType::SurfaceElectricFieldMap);
                if (info != nullptr)
                {
                    info->m_currentFrequencyIndex = elemModel.attribute("CurrentFrequencyIndex").toInt();
                    info->m_valueGroupNameIndex = elemModel.attribute("ValueGroupNameIndex").toInt();
                    info->m_valueComponentIndex = elemModel.attribute("ValueComponentIndex").toInt();

                    auto _geometryFileNameStr = elemModel.attribute("GeometryFileName");
                    info->m_geometryFileName = _geometryFileNameStr.split(";");
                    for (auto& _filePath : info->m_geometryFileName)
                    {
                        auto isSuc = GlobalHelperInstance->CurrentInstallationDirectoryPathConversion(_filePath);
                    }

                    if ((!info->m_allCellArray.isEmpty() || !info->m_allPointArray.isEmpty())&& info->m_valueGroupNameIndex != -1)
                    {
                        auto _tempArrayList = info->m_allPointArray + info->m_allCellArray;
                        info->m_currentScalarArray = _tempArrayList[info->m_valueGroupNameIndex];
                    }
                    info->m_graph = this;
                    this->addGraph3D(info);
                    info->readFromProjectFile(&elemModel, GraphType::SurfaceElectricFieldMap, isdiso);
                    slot_updateSetting(info->m_surfaceElectricFieldMapSettingData);

                    auto _curveNameListWidget = m_sidebarSettings->getCurveNameListWidget();
                    emit IBaseSignalInstance->signal_surfaceElectricFieldMapSidebarCurveNameClicked(m_windowId, {_curveNameListWidget->row(info->m_sidebarItem)});
                    if (!info->m_SEFMSidebarData->getIsShowActor())
                        emit IBaseSignalInstance->signal_surfaceElectricFieldMapSidebarItemCheckStateChanged(m_windowId, _curveNameListWidget->row(info->m_sidebarItem), info->m_SEFMSidebarData->getIsShowActor());
                    if (!info->m_allCellArray.isEmpty() || !info->m_allPointArray.isEmpty())
                    {
                        auto _tempArrayList = info->m_allPointArray + info->m_allCellArray;
                        auto _index = _tempArrayList.indexOf(info->m_SEFMSidebarData->getCurrentScalarArray());
                        if (_index != -1)
                            emit IBaseSignalInstance->signal_surfaceElectricFieldMapSidebarResultDataChanged(m_windowId, _index);
                    }
                }
            }
        }
        readFromProjectFile3DWindowBase(element);
    }

    void SurfaceElectricFieldMapWindow::addGraph3D(InfomationGraph3DBasical* info)
    {
        auto reader = info->m_reader;
        if (reader == nullptr)
        {
            return;
        }
        m_graphInfoList.append(info);
        if (!GlobalHelperInstance->getIsOpenProject())
            info->m_informationID = WindowTotalDataInstance->getGraph3DInformationMaxID();
        WindowTotalDataInstance->appendInfomationGraph3DBasical(info);

        // 添加曲线名字到侧边栏
        //info->m_name = info->m_name + "_" + QString::number(++graphNum);
        QListWidgetItem* item = m_sidebarSettings->addData(info);
        info->m_sidebarItem = item;
        // InfomationGraph3DBasical* currentInfo = m_curveMap[item];

        auto fieldGraphGenerator = new FieldGraphGenerator(this);
        info->m_fieldGraphGenerator = fieldGraphGenerator;
        fieldGraphGenerator->SetInputDataSet(info->m_data);

        int _mapSettingDataID = -1;
        if (!GlobalHelperInstance->getIsOpenProject())
            _mapSettingDataID = WindowTotalDataInstance->getSurfaceElectricFieldMapMainSettingDataMaxID();
        SurfaceElectricFieldMapSettingData* data = new SurfaceElectricFieldMapSettingData(this, _mapSettingDataID);
        ResultDataSettingData* resultDataSettingData = new ResultDataSettingData(this);
        //data->setGeometrySettingData(m_geometrySettingData);
        data->setCubeAxesActorSettingData(m_cubeAxesSettingData);
        data->setResultDataSettingData(resultDataSettingData);

        QColor color;
        double* range{ nullptr };
        if (info->m_valueGroupNameIndex == -1)
        {
            fieldGraphGenerator->SetGeometryActorColor(1, 0, 0);
            fieldGraphGenerator->UpdateGeometryActor();
            auto geometryActor = fieldGraphGenerator->GetGeometryActor();

#ifndef _DEBUG
            geometryActor->Print(std::cout);
#endif
            // 设置名字
            auto dataType = info->m_resultType;//表面场图不允许添加多个图，因此只设置一个颜色条
            auto scalarBarType = getScalarBarType(dataType);
            if (!m_eachTypeGraphCount.contains(scalarBarType))
            {
                m_eachTypeGraphCount[scalarBarType] = 1;
                info->m_graphIDFromType = 1;
            }
            else
            {
                m_eachTypeGraphCount[scalarBarType] += 1;
                info->m_graphIDFromType = m_eachTypeGraphCount[scalarBarType];
            }


            m_render3D->AddActor(geometryActor);
            info->m_actor = geometryActor;
        }
        else
        {
            const auto& currentField = info->m_currentScalarArray;

            bool isSetSuccess = false;
            if (info->m_resultType == 6)//表面电势分布默认取对数
            {
                info->m_isLog = true;
                auto logFactory = decideLogCoefficients(info->m_resultType);
                 isSetSuccess = fieldGraphGenerator->SetActiveScalarAttribute(
                     currentField.arrayIndex, currentField.type, 0, true, logFactory);

                 if (!isSetSuccess)
                 {
                     auto errorMsg = fieldGraphGenerator->getErrorMessage();
                     if (!GlobalHelperInstance->getIsOpenProject())
                        emit IBaseSignalInstance->signal_sendErrorMessageToUI(errorMsg);
                     //根据需求，如果取对数失败，则不取对数按原始数值显示
                     info->m_isLog = false;
                     isSetSuccess = fieldGraphGenerator->SetActiveScalarAttribute(
                         currentField.arrayIndex, currentField.type, 0);
                 }
            }
            else
            {
                 isSetSuccess = fieldGraphGenerator->SetActiveScalarAttribute(
                    currentField.arrayIndex, currentField.type, 0);
            }
            if (!isSetSuccess)
            {
                auto errorMsg = fieldGraphGenerator->getErrorMessage();
                if (!GlobalHelperInstance->getIsOpenProject())
                    emit IBaseSignalInstance->signal_sendErrorMessageToUI(errorMsg);
                return;
            }
            fieldGraphGenerator->UpdateScalarFieldActor();
            auto scalarDataActor = fieldGraphGenerator->GetScalarsFieldActor();
            m_render3D->AddActor(scalarDataActor);
            info->m_actor = scalarDataActor;

            // 设置颜色条
            auto dataType = info->m_resultType;//表面场图不允许添加多个图，因此只设置一个颜色条
            auto scalarBarType = getScalarBarType(dataType);
            if (!m_scalarBarGeneratorMap.contains(scalarBarType))
            {
                m_scalarBarGeneratorMap[scalarBarType] = new FieldScalarBarGenerator(m_render3D, this);
                m_eachTypeGraphCount[scalarBarType] = 1;
                info->m_graphIDFromType = 1;
                // 创建双击事件回调
                m_doubleClickCallback->addCallbackObjectSlot(m_scalarBarGeneratorMap[scalarBarType]->getScalarBarActor(), this, "slot_scalarBarDoubleClicked");
            }
            else
            {
                m_eachTypeGraphCount[scalarBarType] += 1;
                info->m_graphIDFromType = m_eachTypeGraphCount[scalarBarType];
            }

            auto columeType = GetResultDataTypeAsString(dataType,false);

            auto scalarBarGenerator = m_scalarBarGeneratorMap[scalarBarType];
            ScalarBarSettingData* scalarBarSettingData = scalarBarGenerator->getScalarBarSettingData();
            data->setScalarBarSettingData(scalarBarSettingData);
            scalarBarSettingData->setScalarBarTitle(columeType);
            scalarBarSettingData->setScalarBarIsLog(info->m_isLog);
            info->m_fieldScalarBarGenerator = scalarBarGenerator;
            info->m_scalarBar = scalarBarGenerator->getScalarBarActor();
            scalarBarGenerator->addGraph(fieldGraphGenerator);

            //设置单位
            QString unit = getUnit(dataType);
            scalarBarSettingData->setScalarBarUnit(unit);
        }
        info->m_surfaceElectricFieldMapSettingData = data;
        //m_dataMap.append(qMakePair(info, data));

        //更新颜色条单位和DB
        updateDBAndUnitData();

        ////设置初始值 几何体
        if (info->m_geometryFileName.empty()) //几何路径为空
        {
            data->setGeometrySettingData(nullptr);
            info->m_geomtryActorGenerator = nullptr;
        }
        else
        {
            std::tuple<QStringList, QObject*, GeomtryActorGenerator*> existGeometryTuple;
            if (isContainGeometryPath(m_geometrySettingTupleList, info->m_geometryFileName, existGeometryTuple))
            {
                auto geometrySettingData = qobject_cast<GeometrySettingData*>(std::get<1>(existGeometryTuple));
                data->setGeometrySettingData(geometrySettingData);
                info->m_geomtryActorGenerator = std::get<2>(existGeometryTuple);
            }
            else
            {
                auto geometrySettingData = new GeometrySettingData(this);
                data->setGeometrySettingData(geometrySettingData);
                GeomtryActorGenerator* generator = new GeomtryActorGenerator(this);
                generator->setFileNameList(info->m_geometryFileName);
                generator->getActor()->SetVisibility(0);
                info->m_geomtryActorGenerator = generator;
                m_render3D->AddActor(generator->getActor());
                m_geometrySettingTupleList.append(std::make_tuple(info->m_geometryFileName, geometrySettingData, generator));
            }
        }

        // 生成侧边栏数据
        generateSidebarSettingData(item, info);
        QSignalBlocker bl(m_sidebarSettings->getCurveNameListWidget());
        item->setText(getSidebarDataFromNameItem(item)->getGraphName());
        item->setToolTip(getSidebarDataFromNameItem(item)->getGraphName());
        info->m_name = getSidebarDataFromNameItem(item)->getGraphName();

        /// 设置初始值 结果数据Actor
        auto resultDataSetting = data->getResultDataSettingData();
        resultDataSetting->setResultDataName(info->m_name);
        resultDataSetting->setResultDataTransparency(0);
        resultDataSetting->setResultDataScaleFactor(1.0);

        bool _noUse = false;
        updateClipperAndGeometry(m_isActiveClip, m_isShowingGeometry, _noUse);

        updateAnimationButtonState();
        updateCubeAxesActor(m_cubeAxesSettingData->getVisibility());

        QFileInfo sourceFile(info->m_filePath);
        auto suffix = sourceFile.suffix();
        QString str;
        if (suffix == "vtk")
        {
            auto _reader = static_cast<MutiVTKFilesReader*>(info->m_reader);
            info->m_geometryFileName = _reader->GetGeometryFileName();
        }
        else if (suffix == "vtu")
        {
            auto _reader = static_cast<MutiVTUFilesReader*>(info->m_reader);
            info->m_geometryFileName = _reader->GetGeometryFileName();
        }
        else if (suffix == "vtp")
        {
            auto _reader = static_cast<VTPFilesReader*>(info->m_reader);
            info->m_geometryFileName = _reader->GetGeometryFileName();
        }
        this->setCameraToIsometric();
    }

    void SurfaceElectricFieldMapWindow::slot_scalarBarDoubleClicked(vtkProp* pickedProp)
    { // 使用 pickedProp 进行处理
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        if (pickedProp == nullptr)
        {
            return;
        }

        // 只有一个数据
        if (m_graphInfoList.size() == 1)
        {
            if (m_graphInfoList[0]->m_scalarBar == pickedProp)
            {
                auto tmp = m_graphInfoList[0]->m_fieldScalarBarGenerator->getLookupTable()->GetRange();
                m_graphInfoList[0]->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData()->setScalarBarMinValue(tmp[0]);
                m_graphInfoList[0]->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData()->setScalarBarMaxValue(tmp[1]);
                m_mainSettingDialog->updateUI(m_graphInfoList[0]->m_surfaceElectricFieldMapSettingData, SurfaceElectricFieldMapSettingDialog::EntryType::ScalarBar);
            }
        }
        // 多个数据
        else
        {
            SurfaceElectricFieldMapSettingData* currentData = nullptr;
            for (const auto& i : m_graphInfoList)
            {
                if (i->m_scalarBar == pickedProp)
                {
                    auto tmp = i->m_fieldScalarBarGenerator->getLookupTable()->GetRange();
                    currentData = i->m_surfaceElectricFieldMapSettingData;
                    currentData->getScalarBarSettingData()->setScalarBarMinValue(tmp[0]);
                    currentData->getScalarBarSettingData()->setScalarBarMaxValue(tmp[1]);
                    //m_mainSettingDialog->updateSettingDataToUI(i.second, ThreeDCloudMapSettingDialog::EntryType::ScalarBar);
                }
            }

            if (isGeometryPathAllSame(m_graphInfoList)) //几何路径全相同
            {
                SurfaceElectricFieldMapSettingData* tempData = new SurfaceElectricFieldMapSettingData(this, -1);
                tempData->setScalarBarSettingData(currentData->getScalarBarSettingData());
                tempData->setGeometrySettingData(currentData->getGeometrySettingData());
                tempData->setResultDataSettingData(nullptr);
                tempData->setCubeAxesActorSettingData(currentData->getCubeAxesActorSettingData());

                m_mainSettingDialog->updateUI(tempData, SurfaceElectricFieldMapSettingDialog::EntryType::ScalarBar);
            }
            else //几何路径不全相同
            {
                SurfaceElectricFieldMapSettingData* tempData = new SurfaceElectricFieldMapSettingData(this, -1);
                tempData->setScalarBarSettingData(currentData->getScalarBarSettingData());
                tempData->setGeometrySettingData(nullptr);
                tempData->setResultDataSettingData(nullptr);
                tempData->setCubeAxesActorSettingData(currentData->getCubeAxesActorSettingData());

                m_mainSettingDialog->updateUI(tempData, SurfaceElectricFieldMapSettingDialog::EntryType::ScalarBar);
            }
        }

        m_mainSettingDialog->execWindow();
    }

    void SurfaceElectricFieldMapWindow::initScalarBarSettingConnection()
    {
        connect(m_mainSettingDialog, &SurfaceElectricFieldMapSettingDialog::signal_updateSetting,
            this, &SurfaceElectricFieldMapWindow::slot_updateSetting);
    }

    void SurfaceElectricFieldMapWindow::initSidebarSettingConnection()
    {
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::siganl_showHideItemActor,
            this, &SurfaceElectricFieldMapWindow::slot_showHideItemActor);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::siganl_graphNameDoubleClicked,
            this, &SurfaceElectricFieldMapWindow::slot_graphNameDoubleClicked);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::signal_chosenItemsChanged,
            this, &SurfaceElectricFieldMapWindow::slot_chosenItemsChanged);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::signal_updateActorValue,
            this, &SurfaceElectricFieldMapWindow::slot_updateActorValue);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::signal_deleteChosenGraphs,
            this, &SurfaceElectricFieldMapWindow::slot_deleteChosenGraphs);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::signal_getSidebarCurveDataSource,
            this, &SurfaceElectricFieldMapWindow::slot_getSidebarCurveDataSource);
    }

    void SurfaceElectricFieldMapWindow::generateSidebarSettingData(QListWidgetItem* item, InfomationGraph3DBasical* info)
    {
        SurfaceElectricFieldMapSidebarData* sideBarData = new SurfaceElectricFieldMapSidebarData(this);
        info->m_SEFMSidebarData = sideBarData;
        sideBarData->setCurrentScalarArray(info->m_currentScalarArray);
        sideBarData->setAllPointArray(info->m_allPointArray);
        sideBarData->setAllCellArray(info->m_allCellArray);
        sideBarData->setCurrentScalarArrayComp(info->m_currentScalarArrayComp);
        auto graphName = generateGraphNameAuto(info);
        sideBarData->setGraphName(graphName);
        sideBarData->setDataSource(info->m_dataSources);
        sideBarData->setIsLog(info->m_isLog);

        sideBarData->setIsGraphNameRenamed(false);
    }

    void SurfaceElectricFieldMapWindow::connectSignalsAndSlots()
    {
        this->m_renderWindow3D->GetInteractor()->AddObserver(vtkCommand::LeftButtonDoubleClickEvent, m_doubleClickCallback);
        connect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::siganl_graphNameDoubleClicked,
            this, &SurfaceElectricFieldMapWindow::slot_graphNameDoubleClicked);
    }

    void SurfaceElectricFieldMapWindow::disconnectSignalsAndSlots()
    {
        this->m_renderWindow3D->GetInteractor()->RemoveObservers(vtkCommand::LeftButtonDoubleClickEvent);
        disconnect(m_sidebarSettings, &SurfaceElectricFieldMapSidebarSettings::siganl_graphNameDoubleClicked,
            this, &SurfaceElectricFieldMapWindow::slot_graphNameDoubleClicked);
    }

    void SurfaceElectricFieldMapWindow::prepareAnimationData()
    {
        // 准备数据
        if (!m_isAnimationDataPrepared)
        {
            for (auto info : m_graphInfoList)
            {
                auto reader = info->m_reader;
                auto suffix = QFileInfo(info->m_filePath).suffix();
                if (suffix.toUpper() == "VTK")
                {
                    QList<MutiVTKFilesReader*> readerList = static_cast<MutiVTKFilesReader*>(reader)->GetOtherList();
                    for (auto everyReader : readerList)
                    {
                        info->m_animationDataList.append(everyReader->GetOutput());
                        if (everyReader == static_cast<MutiVTKFilesReader*>(reader))
                        {
                            info->m_currentAnimationIndex = readerList.indexOf(everyReader);
                        }
                    }
                }
                else if (suffix.toUpper() == "VTU")
                {
                    QList<MutiVTUFilesReader*> readerList = static_cast<MutiVTUFilesReader*>(reader)->GetOtherList();
                    for (auto everyReader : readerList)
                    {
                        info->m_animationDataList.append(everyReader->GetOutput());
                        if (everyReader == static_cast<MutiVTUFilesReader*>(reader))
                        {
                            info->m_currentAnimationIndex = readerList.indexOf(everyReader);
                        }
                    }
                }
                else if (suffix.toUpper() == "VTP")
                {
                    QList<VTPFilesReader*> readerList = static_cast<VTPFilesReader*>(reader)->GetOtherList();
                    for (auto everyReader : readerList)
                    {
                        info->m_animationDataList.append(everyReader->GetOutput());
                        if (everyReader == static_cast<VTPFilesReader*>(reader))
                        {
                            info->m_currentAnimationIndex = readerList.indexOf(everyReader);
                        }
                    }
                }
                m_imageSize < info->m_animationDataList.size() ? m_imageSize = info->m_animationDataList.size() : m_imageSize = m_imageSize;
            }

            m_isAnimationDataPrepared = true;
        }
    }

    void SurfaceElectricFieldMapWindow::removeActorWithMarker(InfomationGraph3DBasical* info)
    {
        FieldGraphGenerator* fieldGraphGenerator = info->m_fieldGraphGenerator;
        if (fieldGraphGenerator == nullptr)
        {
            qDebug() << "Error: " << __FILE__ << " " << __LINE__ << " Chosen data's generator not exist!";
            return;
        }
        auto actor = info->m_actor;
        auto scalarBaractor = info->m_scalarBar;

        QList<Marker3DDataInfo*> toDeleteList;
        QList<int> toDeleteTableIndexs;
        auto innerMatrkerTable = m_markerDataTable->getInnerTableWidget();

        for (const auto& i : m_marker3DDataInfoList)
        {
            if (i->m_sourceActor == actor)
            {
                m_render3D->RemoveActor(i->m_markerActor);
                m_render3D->RemoveActor(i->m_markerTextActor);

                // 同步markerTable可见性
                for (int row = 0; row < innerMatrkerTable->rowCount(); ++row)
                {
                    if (innerMatrkerTable->item(row, 0)->text().toInt() == i->m_markerId)
                    {
                        toDeleteTableIndexs.append(row);
                    }
                }
                toDeleteList.append(i);
            }
        }
        for (const auto& i : toDeleteList)
        {
            int key = m_marker3DDataInfoList.key(i);
            m_marker3DDataInfoList.remove(key);
        }
        std::sort(toDeleteTableIndexs.begin(), toDeleteTableIndexs.end());
        for (int i = toDeleteTableIndexs.size() - 1; i >= 0; --i)
        {
            innerMatrkerTable->removeRow(toDeleteTableIndexs.at(i));
        }
        if (innerMatrkerTable->rowCount() == 0)
        {
            m_markerDataTable->hide();
        }
        m_render3D->RemoveActor(actor);

        if (info->m_fieldScalarBarGenerator != nullptr)
        {
            auto scalarBarWidget = info->m_fieldScalarBarGenerator->getScalarBarWidget();
            info->m_fieldScalarBarGenerator->removeAGraph(fieldGraphGenerator);

            bool leftSameType = false;//是否还有同类型的actor存在
            for (auto i : m_graphInfoList)
            {
                if (i == info)
                {
                    continue;
                }

                //判断类型是否相同
                if (info->m_resultType == i->m_resultType)
                {
                    leftSameType = true;
                    break;
                }
            }

            if (!leftSameType)
            {
                m_render3D->RemoveActor(scalarBaractor);
                scalarBarWidget->SetEnabled(false);
            }
        }
        qDebug() << "info->m_scalarBar = " << info->m_scalarBar;
        //if (clipperGerator != nullptr)
        //{
        //    m_render3D->RemoveActor(clipperGerator->getClipActor());
        //}
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::updateMarkerValue()
    {
        auto tableWidget = m_markerDataTable->getInnerTableWidget();
        for (int i = 0; i < tableWidget->rowCount(); ++i)
        {
            // 不显示的不更新，不显示包括（可见性为false和显示类型不同）
            // 因此更新actor可见性时，需要调用本函数
            if (tableWidget->isRowHidden(i))
            {
                continue;
            }

            int markerId = tableWidget->item(i, 0)->text().toInt();
            Marker3DDataInfo* markerInfo = m_marker3DDataInfoList.value(markerId);
            if (markerInfo == nullptr)
            {
                continue;
            }

            auto dataSet = markerInfo->m_sourceActor->GetMapper()->GetInput();
            if (!dataSet)
            {
                return;
            }

            auto curveNameWidget = m_sidebarSettings->getCurveNameListWidget();
            for (int row = 0; row < curveNameWidget->count(); ++row)
            {
                QListWidgetItem* item = curveNameWidget->item(row);
                auto graphInfo = getInfoFromSidebarNameItem(item);
                FieldGraphGenerator::ArrayInformation currentArray = graphInfo->m_currentScalarArray;
                if (graphInfo->m_actor != markerInfo->m_sourceActor|| currentArray.arrayIndex != markerInfo->m_fieldIndex)
                {
                    continue;
                }


                if (currentArray.type == FieldGraphGenerator::StructureType::POINTS) // 当前激活的场是cell
                {
                    if (markerInfo->m_markerType == 0)
                    {
                        auto activeArray = graphInfo->m_fieldGraphGenerator->getUsingData()->GetPointData()->GetScalars();
                        QString pickedValue = "null";
                        if (activeArray != nullptr) // 原数据有激活point场
                        {
                            if (markerInfo->m_pickedId < graphInfo->m_fieldGraphGenerator->getUsingData()->GetNumberOfPoints())
                            {
                                double value = activeArray->GetComponent(markerInfo->m_pickedId, 0);
                                pickedValue = QString::number(value);

                                tableWidget->item(i, 5)->setText(QString::number(value));
                                markerInfo->m_markerValue = value;
                            }
                            else
                            {
                                qDebug() << "Error:currentPointId is out of range";
                            }
                        }
                    }
                    //else
                    //{
                    //    tableWidget->item(i, 4)->setText("null");
                    //    markerInfo->m_markerValue = "null";
                    //}
                }
                else // 当前激活的场是cell
                {
                    if (markerInfo->m_markerType == 1)
                    {
                        auto activeArray = dataSet->GetCellData()->GetScalars();
                        QString pickedValue = "null";
                        if (activeArray != nullptr) // 原数据有激活cell场
                        {
                            if (markerInfo->m_pickedId < dataSet->GetNumberOfCells())
                            {
                                double value = activeArray->GetComponent(markerInfo->m_pickedId, 0);
                                pickedValue = QString::number(value);

                                tableWidget->item(i, 5)->setText(QString::number(value));
                                markerInfo->m_markerValue = value;
                            }
                            else
                            {
                                qDebug() << "Error:currentPointId is out of range";
                            }
                        }
                    }
                    //else
                    //{
                    //    tableWidget->item(i, 4)->setText("null");
                    //    markerInfo->m_markerValue = "null";
                    //}
                }
            }
        }
    }

    bool SurfaceElectricFieldMapWindow::isInfoContainsMultipleData(const InfomationGraph3DBasical* info)
    {
        auto reader = info->m_reader;
        if (reader == nullptr)
        {
            return false;
        }
        auto suffix = QFileInfo(info->m_filePath).suffix();

        if (suffix.toUpper() == "VTK")
        {
            QList<MutiVTKFilesReader*> readerList = static_cast<MutiVTKFilesReader*>(reader)->GetOtherList();
            if (readerList.size() <= 1)
            {
                return false;
            }
        }
        else if (suffix.toUpper() == "VTU")
        {
            QList<MutiVTUFilesReader*> readerList = static_cast<MutiVTUFilesReader*>(reader)->GetOtherList();
            if (readerList.size() <= 1)
            {
                return false;
            }
        }
        else if (suffix.toUpper() == "VTP")
        {
            QList<VTPFilesReader*> readerList = static_cast<VTPFilesReader*>(reader)->GetOtherList();
            if (readerList.size() <= 1)
            {
                return false;
            }
        }

        return true;
    }

    bool SurfaceElectricFieldMapWindow::isInfoFromSameSource(QList<InfomationGraph3DBasical*> infoList)
    {
        if (infoList.isEmpty())
        {
            return false;
        }

        QString _folderPath{ "" };
        int count = 0;
        for (const auto& info : infoList)
        {
            QString filePath = info->m_filePath;
            QFileInfo fileInfo(filePath);
            QString folderPath = fileInfo.absolutePath();

            if (folderPath.isEmpty())
            {
                return false;
            }

            if (count == 0)
            {
                _folderPath = folderPath;
                ++count;
                continue;
            }

            if (folderPath != _folderPath)
            {
                return false;
            }
        }
        return true;
    }

    bool SurfaceElectricFieldMapWindow::whetherCanEnableDataAnimation()
    {
        if (m_graphInfoList.size() != 1)
        {
            return false;
        }

        return isInfoContainsMultipleData(m_graphInfoList[0]) ? true : false;
    }

    bool SurfaceElectricFieldMapWindow::whetherCanEnableThunderstormZone()
    {
        auto item = getSurfacePotentialDistributionSourceItem();
        return item == nullptr ? false : true;
    }

    QStandardItem* SurfaceElectricFieldMapWindow::getSurfacePotentialDistributionSourceItem()
    {
        for (auto i : m_graphInfoList)
        {
            if (i->m_resultType == 6)
            {
                return i->m_projectTreeSourceItem;
            }
        }
        return nullptr;
    }

    void SurfaceElectricFieldMapWindow::sentToolBarAnimationDataInfo(const InfomationGraph3DBasical* info)
    {
        auto& currentFrameID = info->m_currentAnimationIndex;

        //右上角显示动图信息
        auto _type = info->m_fieldType;
        auto unit = info->m_unit;
        QList<double> varValueList = info->m_VarValueList;

        QString typeString{};

        if (m_animationType == 0)//数据变换
        {
            if (_type == 1)
            {
                typeString = "时间";
            }
            else if (_type == 2)
            {
                typeString = "频率";//三维曲面图数据变化始终是频率
            }
        }
        else //相机
        {
            typeString = "角度";
            unit = "deg";
        }

        //TODO 拿到变量名称

        auto currentFrequency = varValueList[currentFrameID];
        QString firstLine = typeString + ": " + QString::number(currentFrequency) + " " + unit;

        auto sameRate = m_animationSettingData->sampleRate();
        QString secondLine = "采样率: " + QString::number(sameRate);

        auto frameRate = m_animationSettingData->frameRate();
        QString thirdLine = "播放速度: " + QString::number(frameRate);

        QStringList textActorList;
        textActorList << firstLine << secondLine << thirdLine;
        setAnimationInfoText(textActorList);

        int totalNum = std::ceil(double(info->m_animationDataList.size()) / sameRate);

        if (m_animationDataCount * sameRate >= info->m_animationDataList.size())
        {
            m_animationDataCount = 0;
        }

        if (m_animationTooBarInfoData != nullptr)
        {
            m_animationTooBarInfoData->setType(typeString);
            m_animationTooBarInfoData->setUnit(unit);
            m_animationTooBarInfoData->setCurrentValue(QString::number(currentFrequency));
            m_animationTooBarInfoData->setSliderCurrentValue(currentFrameID);
            m_animationTooBarInfoData->setSliderMaxValue(totalNum);
        }

        emit IWidgetSignalInstance->signal_setToolBarAnimationDataInfo(typeString, unit, currentFrequency, totalNum, m_animationDataCount);
        ++m_animationDataCount;
    }

    void SurfaceElectricFieldMapWindow::slot_scalarBarFontTypeChanged(vtkScalarBarActor* scalarBarActor, QString fontType)
    {
        if (scalarBarActor == nullptr)
        {
            return;
        }
        if (fontType == "微软雅黑") // 并非真正的微软雅黑
        {
            QString currenEXEPath = QCoreApplication::applicationDirPath();
            auto micFont = currenEXEPath + "/Fonts/Alibaba-PuHuiTi-Regular.ttf";
            scalarBarActor->GetTitleTextProperty()->SetFontFamily(VTK_FONT_FILE);
            scalarBarActor->GetTitleTextProperty()->SetFontFile(micFont.toLocal8Bit());
        }
        else if (fontType == "宋体") // 并非真正的宋体
        {
            QString currenEXEPath = QCoreApplication::applicationDirPath();
            auto songFont = currenEXEPath + "/Fonts/TangXianBinSong-2.otf";
            scalarBarActor->GetTitleTextProperty()->SetFontFamily(VTK_FONT_FILE);
            scalarBarActor->GetTitleTextProperty()->SetFontFile(songFont.toLocal8Bit());
        }
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::slot_updateSetting(SurfaceElectricFieldMapSettingData* data)
    {
        //几何
        auto _geometrySettingData = data->getGeometrySettingData();
        if (_geometrySettingData != nullptr)
        {
            for (const auto& i : m_graphInfoList)
            {
                if (i->m_surfaceElectricFieldMapSettingData->getGeometrySettingData() == _geometrySettingData)
                {
                    auto info = i;
                    auto _geometryTransparency = _geometrySettingData->getGeometryTransparency();
                    if (info->m_geomtryActorGenerator != nullptr)
                    {
                        info->m_geomtryActorGenerator->getActor()->GetProperty()->SetOpacity(1 - _geometryTransparency / 100.);
                        if (_geometryTransparency == 100)
                        {
                            info->m_geomtryActorGenerator->getActor()->VisibilityOff();
                        }
                        else
                        {
                            info->m_geomtryActorGenerator->getActor()->SetVisibility(m_isShowingGeometry);
                        }
                    }
                    break;
                }
            }
        }

        //结果
        auto _resultSettingData = data->getResultDataSettingData();
        if (_resultSettingData != nullptr)
        {
            for (const auto& i : m_graphInfoList)
            {
                if (i->m_surfaceElectricFieldMapSettingData->getResultDataSettingData() == _resultSettingData)
                {
                    auto info = i;
                    auto _actorName = _resultSettingData->getResultDataName();
                    auto _transparency = _resultSettingData->getResultDataTransparency();
                    auto _scaleFactor = _resultSettingData->getResultDataScaleFactor();

                    info->m_actor->GetProperty()->SetOpacity(1 - _transparency / 100.);
                    if (_transparency == 100)
                    {
                        info->m_actor->VisibilityOff();
                    }
                    else
                    {
                        auto visbility = info->m_sidebarItem->checkState();
                        info->m_actor->SetVisibility(visbility);
                    }
                    synchronousActorName(info, _actorName);
                    break;
                }
            }

        }

        //包围盒
        if (data->getCubeAxesActorSettingData())
        {
            updateCubeAxesActor(data->getCubeAxesActorSettingData()->getVisibility());
        }

        updateClipperPlaneActor();
        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();

        auto _scalarBarSettingData = data->getScalarBarSettingData();
        if (_scalarBarSettingData != nullptr)
        {
            for (const auto& i : m_graphInfoList)
            {
                if (i->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData() == _scalarBarSettingData)
                {
                    auto info = i;
                    auto tmp = info->m_fieldScalarBarGenerator->getLookupTable()->GetRange();
                    m_mainSettingDialog->setScalarBarCustomRange(tmp[0], tmp[1]);
                }
            }
        }
        

    }

    void SurfaceElectricFieldMapWindow::slot_showHideItemActor(QListWidgetItem* item)
    {
        if (item == nullptr)
            return;
        InfomationGraph3DBasical* info = getInfoFromSidebarNameItem(item);
        FieldGraphGenerator* fieldGraphGenerator = info->m_fieldGraphGenerator;
        if (fieldGraphGenerator == nullptr)
        {
            qDebug() << "Error: " << __FILE__ << " " << __LINE__ << " Chosen data's generator not exist!";
            return;
        }
        auto dataActor = info->m_actor;
        if (dataActor == nullptr)
        {
            qDebug() << "Error: " << __FILE__ << " " << __LINE__ << " Data actor is empty!";
            return;
        }

        auto checkState = item->checkState() == Qt::Checked ? true : false;
        info->m_SEFMSidebarData->setIsShowActor(checkState);

        info->m_fieldGraphGenerator->GetScalarsFieldActor()->SetVisibility(checkState);
        info->m_fieldGraphGenerator->GetGeometryActor()->SetVisibility(checkState);


        if (info->m_fieldScalarBarGenerator != nullptr)
        {
            bool isSameTypeAllHide = true;
            for (auto i : m_graphInfoList)
            {
                //判断类型是否相同
                if (info->m_resultType == i->m_resultType)
                {
                    if (i->m_fieldGraphGenerator->GetScalarsFieldActor()->GetVisibility())
                    {
                        isSameTypeAllHide = false;
                        break;
                    }
                }
            }
            info->m_fieldScalarBarGenerator->getScalarBarActor()->SetVisibility(!isSameTypeAllHide);
            info->m_fieldScalarBarGenerator->getScalarBarWidget()->SetEnabled(!isSameTypeAllHide);
        }
        
        //设置marker的可见性，放在这里是因为marker的可见性依赖于数据actor的可见性
        updateMarkerVisibility();

        updateClipperPlaneActor();
        updateMarkerValue();
        updateCubeAxesActor(m_cubeAxesSettingData->getVisibility());
        m_render3D->ResetCamera();
        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::animationToNextDataFrame()
    {
        for (auto info : m_graphInfoList)
        {
            auto fieldGraphGenerator = info->m_fieldGraphGenerator;
            if (fieldGraphGenerator == nullptr)
            {
                continue;
            }
            auto& currentFrameID = info->m_currentAnimationIndex;

            if (m_isFirstTimeDataAnimation)//第一次进行数据动图时，始终播放第一帧
            {
                currentFrameID = 0;
                m_isFirstTimeDataAnimation = false;
            }
            else
            {
                int tempID = currentFrameID + m_animationSettingData->sampleRate();
                currentFrameID = tempID >= info->m_animationDataList.size() ? 0 : tempID;
            }
            if (m_isBeginExportAnimation)//是从导出动图启动，始终播放第一帧
            {
                currentFrameID = 0;
                m_isBeginExportAnimation = false;
                m_animationDataCount = 0;
            }
            qDebug() << "currentFrameID: " << currentFrameID;

            // 更新info存储的reader和path信息
            QFileInfo sourceFile(info->m_filePath);
            auto suffix = sourceFile.suffix();
            QString str;
            if (suffix == "vtk")
            {
                auto _reader = static_cast<MutiVTKFilesReader*>(info->m_reader)->GetOtherList().at(currentFrameID);
                info->m_reader = _reader;
                info->m_geometryFileName = _reader->GetGeometryFileName();
                info->m_filePath = _reader->GetFileName();
            }
            else if (suffix == "vtu")
            {
                auto _reader = static_cast<MutiVTUFilesReader*>(info->m_reader)->GetOtherList().at(currentFrameID);
                info->m_reader = _reader;
                info->m_geometryFileName = _reader->GetGeometryFileName();
                info->m_filePath = _reader->GetFileName();
            }
            else if (suffix == "vtp")
            {
                auto _reader = static_cast<VTPFilesReader*>(info->m_reader)->GetOtherList().at(currentFrameID);
                info->m_reader = _reader;
                info->m_geometryFileName = _reader->GetGeometryFileName();
                info->m_filePath = _reader->GetFileName();
            }

            fieldGraphGenerator->SetInputDataSet(info->m_animationDataList.at(currentFrameID));

            if (info->m_valueGroupNameIndex != -1)
            {
                auto item = info->m_sidebarItem;
                auto sidebarData = info->m_SEFMSidebarData;
                auto isLog = sidebarData->getIsLog();
                info->m_isLog = isLog;
                auto isNor = sidebarData->getIsNormalized();
                auto type = info->m_resultType;
                auto logFactory = decideLogCoefficients(type);

                const auto& currentField = info->m_currentScalarArray;
                auto isSetSuccess = fieldGraphGenerator->SetActiveScalarAttribute(
                    currentField.arrayIndex, currentField.type, 0, isLog, logFactory, isNor);
                if (!isSetSuccess)
                {
                    return;
                }
                fieldGraphGenerator->UpdateScalarFieldActor();
            }
            else
            {
                fieldGraphGenerator->UpdateGeometryActor();
            }

            //更新数据源
            auto item = info->m_sidebarItem;
            QString dataSource;
            slot_getSidebarCurveDataSource(item, dataSource);
            auto data = info->m_SEFMSidebarData;
            data->setDataSource(dataSource);
            if (item->isSelected())
            {
                m_sidebarSettings->updateInfoDataAndInterfaceToUI(data);
            }
            sentToolBarAnimationDataInfo(info);
        }

        updateMarkerValue();
        updateCubeAxesActor(m_cubeAxesSettingData->getVisibility());
        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::slot_graphNameDoubleClicked(QListWidgetItem* item)
    {
        InfomationGraph3DBasical* info = getInfoFromSidebarNameItem(item);
        if (info == nullptr) return;
        for (auto i : m_graphInfoList)
        {
            if (i == info)
            {
                info->m_valueGroupNameIndex == -1 ? m_mainSettingDialog->setScalarBarSettingUIEnabled(false) : m_mainSettingDialog->setScalarBarSettingUIEnabled(true);

                if (info->m_valueGroupNameIndex != -1)
                {
                    auto tmp = info->m_fieldScalarBarGenerator->getLookupTable()->GetRange();
                    i->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData()->setScalarBarMinValue(tmp[0]);
                    i->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData()->setScalarBarMaxValue(tmp[1]);
                    m_mainSettingDialog->setScalarBarCustomRange(tmp[0], tmp[1]);
                }
                m_mainSettingDialog->updateUI(i->m_surfaceElectricFieldMapSettingData, SurfaceElectricFieldMapSettingDialog::EntryType::ResultData);
            }
        }
        m_mainSettingDialog->execWindow();
    }

    void SurfaceElectricFieldMapWindow::slot_updateActorValue(SurfaceElectricFieldMapSidebarData* data)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto info = getGraph3DInfoFromSidebarData(data);
        auto item = info->m_sidebarItem;
        auto fieldGraphGenerator = info->m_fieldGraphGenerator;
        if (fieldGraphGenerator == nullptr)
        {
            qDebug() << "Error: " << __FILE__ << " " << __LINE__ << " Chosen data's generator not exist!";
            return;
        }
        auto isLog = data->getIsLog();
        info->m_isLog = isLog;
        auto isNor = data->getIsNormalized();
        auto type = info->m_resultType;
        auto logFactory = decideLogCoefficients(type);
        auto currentArray = data->getCurrentScalarArray();
        auto isSetSuccess = fieldGraphGenerator->SetActiveScalarAttribute(currentArray.arrayIndex, currentArray.type, currentArray.arrayComponent, isLog, logFactory, isNor);
        if (!isSetSuccess)
        {
            auto errorMsg = fieldGraphGenerator->getErrorMessage();
            emit IBaseSignalInstance->signal_sendErrorMessageToUI(errorMsg);
            data->setIsLog(false);
            info->m_isLog = false;
            m_sidebarSettings->updateInfoDataAndInterfaceToUI(data);
            return;
        }
        fieldGraphGenerator->UpdateScalarFieldActor();
        info->m_currentScalarArray = currentArray;
        
        if (!info->m_isGraphRenamed)
        {
            auto name = generateGraphNameAuto(info);
            QSignalBlocker bl(m_sidebarSettings->getCurveNameListWidget());
            item->setText(name);
            item->setToolTip(name);

            info->m_name = name;

            for (auto i : m_graphInfoList)
            {
                if (i == info)
                {
                    i->m_surfaceElectricFieldMapSettingData->getResultDataSettingData()->setResultDataName(name);
                }
            }
        }

        updateMarkerValue();
        updateDBAndUnitData();
        updateDataActorPickable();
        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::slot_chosenItemsChanged(const QList<QListWidgetItem*>& itemList)
    {
        auto info = getInfoFromSidebarNameItem(itemList.at(0));
        SurfaceElectricFieldMapSidebarData* data = info->m_SEFMSidebarData;
        // data->PrintSelf();
        m_sidebarSettings->updateInfoDataAndInterfaceToUI(data);
    }

    void SurfaceElectricFieldMapWindow::slot_deleteChosenGraphs(const QList<QListWidgetItem*>& itemList)
    {
        auto curveNameWidget = m_sidebarSettings->getCurveNameListWidget();
        for (QListWidgetItem* item : itemList)
        {
            auto _infoID = getInfoFromSidebarNameItem(item)->m_informationID;
            WindowTotalDataInstance->removeInfomationGraph3DBasicalByID(_infoID);
            //m_sideBarSettingData.remove(item);

            int row = curveNameWidget->row(item);
            if (row != -1)
            {
                m_sidebarSettings->clearControlPlane();//先清除再删除，删除会触发slot_curveNameClicked
                delete curveNameWidget->takeItem(row);
            }
        }

        for (const auto& item : itemList)
        {
            if (item == nullptr)
                return;
            InfomationGraph3DBasical* info = getInfoFromSidebarNameItem(item);

            int count = 0;
            for (const auto& i : m_graphInfoList)
            {
                if (i->m_geometryFileName == info->m_geometryFileName)
                {
                    count++;
                }
            }

            if (count < 2)//是该路径的唯一一个几何体
            {
                if (info->m_geomtryActorGenerator != nullptr)//删除几何体
                {
                    m_render3D->RemoveActor(info->m_geomtryActorGenerator->getActor());

                    //清除设置
                    for (int i = m_geometrySettingTupleList.size() - 1; i >= 0; --i)
                    {
                        if (std::get<0>(m_geometrySettingTupleList[i]) == info->m_geometryFileName)
                        {
                            m_geometrySettingTupleList.removeAt(i);
                        }
                    }
                }
            }

            removeActorWithMarker(info);
            m_graphInfoList.removeOne(info);

            //for (auto i : m_dataMap)
            //{
            //    if (i.first == info)
            //    {
            //        m_dataMap.removeOne(i);
            //        break;
            //    }
            //}
        }

        updateClipperPlaneActor();
        //m_sidebarSettings->clearControlPlane();
        updateDBAndUnitData();
        emit IWidgetSignalInstance->signal_updateThunderstormZoneButtonState();//更新雷电分区按钮
        updateModelDisplayAndClipperButtonCheckState();
        updateAnimationButtonState();//放在updateModelDisplayAndClipperButtonCheckState之后

        updateCubeAxesActor(m_cubeAxesSettingData->getVisibility());
        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::slot_getSidebarCurveDataSource(QListWidgetItem* item, QString& dataSource)
    {
        InfomationGraph3DBasical* info = getInfoFromSidebarNameItem(item);
        if (info != nullptr)
        {
            emit IWidgetSignalInstance->signal_getThreeDDataSources(info->m_reader, dataSource);
        }
    }

    void SurfaceElectricFieldMapWindow::slot_closeTree(const QList<QStandardItem*>& items)
    {
        QList<QListWidgetItem*> itemToDelete;
        for (auto treeItem : items)
        {
            for (auto info : m_graphInfoList)
            {
                if (info->m_projectTreeSourceItem == treeItem)
                {
                    auto sidebarItem = info->m_sidebarItem;
                    itemToDelete.append(sidebarItem);
                }
            }
        }
        slot_deleteChosenGraphs(itemToDelete);
    }

    void SurfaceElectricFieldMapWindow::pyCurveNameClicked(QList<int> selectedIndexs)
    {
        m_sidebarSettings->pyCurveNameClicked(selectedIndexs);
    }

    void SurfaceElectricFieldMapWindow::pyResultDataChanged(int index)
    {
        m_sidebarSettings->pyResultDataChanged(index);
    }

    void SurfaceElectricFieldMapWindow::pyUpdateProcessData(bool isLog, bool isNormalize)
    {
        m_sidebarSettings->pyUpdateProcessData(isLog, isNormalize);
    }

    void SurfaceElectricFieldMapWindow::pyNameItemRename(int itemIndex, QString newName)
    {
        auto listWidget = m_sidebarSettings->getCurveNameListWidget();
        QListWidgetItem* item = listWidget->item(itemIndex);
        QString curText = item->text();
        item->setText(newName);
    }

    void SurfaceElectricFieldMapWindow::pyDeleteSurfaceElectricFieldMap(QString selectedIndexs)
    {
        m_sidebarSettings->pyDeleteSurfaceElectricFieldMap(selectedIndexs);
    }

    void SurfaceElectricFieldMapWindow::pyItemCheckStateChanged(int itemIndex, bool visible)
    {
        m_sidebarSettings->pyItemCheckStateChanged(itemIndex, visible);
    }

    void SurfaceElectricFieldMapWindow::pySaveSurfaceElectricFieldMapMainSettingData(int type, int settingDataId,
        bool scalarBarIsAutoRange, double scalarBarMin, double scalarBarMax,
        bool scalarBarIsShowTitle, QString scalarBarTitle, QString scalarBarFontColor, int scalarBarFontSize,
        int geometryTransparency, QString resultGraphName, int resultGraphModelTransparency, bool cubeAxesIsVisible)
    {
        for (auto i : m_graphInfoList)
        {
            if (i->m_surfaceElectricFieldMapSettingData->getID() == settingDataId)
            {
                QList<int> _scalarBarFontColor = GlobalHelperInstance->convertStringToIntList(scalarBarFontColor);
                QColor color(_scalarBarFontColor[0], _scalarBarFontColor[1], _scalarBarFontColor[2]);

                auto data = i->m_surfaceElectricFieldMapSettingData;
                auto scalarBarSettingData = data->getScalarBarSettingData();
                if (scalarBarSettingData != nullptr)
                {
                    scalarBarSettingData->setScalarBarAutoRange(scalarBarIsAutoRange);
                    scalarBarSettingData->setScalarBarMinValue(scalarBarMin);
                    scalarBarSettingData->setScalarBarMaxValue(scalarBarMax);
                    scalarBarSettingData->setScalarBarIsShowTitle(scalarBarIsShowTitle);
                    scalarBarSettingData->setScalarBarTitle(scalarBarTitle);
                    scalarBarSettingData->setScalarBarTitleColor(color);
                    scalarBarSettingData->setScalarBarFontSize(scalarBarFontSize);
                }

                if (data->getGeometrySettingData())
                {
                    data->getGeometrySettingData()->setGeometryTransparency(geometryTransparency);
                }
                data->getResultDataSettingData()->setResultDataName(resultGraphName);
                data->getResultDataSettingData()->setResultDataTransparency(resultGraphModelTransparency);
                if (data->getCubeAxesActorSettingData())
                {
                    data->getCubeAxesActorSettingData()->setVisibility(cubeAxesIsVisible);
                }

                slot_updateSetting(data);
                // m_mainSettingDialog->setType((pst::SurfaceElectricFieldMapSettingDialog::EntryType)type);
            }
        }
    }


    QString SurfaceElectricFieldMapWindow::generateGraphNameAuto(InfomationGraph3DBasical* info) const
    {
        auto fileType = info->m_resultType;
        auto graphId = info->m_graphIDFromType;
        auto arrayName = info->m_currentScalarArray.arrayName;
        auto typeString = GetResultDataTypeAsString(fileType, false);
        QString graphName;
        if (arrayName.isEmpty())
        {
            graphName = typeString + "_" + QString::number(graphId);
            while (getHasSameName(graphName))
            {
                graphName += "_1";
            }
            info->m_dataSources = "";
        }
        else
        {
            graphName = typeString + "_" + QString::number(graphId) + "[" + arrayName + "]";
        }
        //info->setDataSources("");
        
        return graphName;
    }


    SurfaceElectricFieldMapSettingData* SurfaceElectricFieldMapWindow::getMainSettingData(InfomationGraph3DBasical* info)
    {
        for (auto i : m_graphInfoList)
        {
            if (i == info)
            {
                return i->m_surfaceElectricFieldMapSettingData;
            }
        }
    }

    void SurfaceElectricFieldMapWindow::updateDBAndUnitData()
    {
        QSet<int> typeProcessed;
        for (auto i : m_graphInfoList)
        {
            auto info = i;

            //以侧边栏同类型的第一个数据为准
            if (typeProcessed.contains(info->m_resultType))
            {
                continue;
            }
            typeProcessed.insert(info->m_resultType);

            auto sliderBarSettingData = i->m_surfaceElectricFieldMapSettingData->getScalarBarSettingData();
            auto nearFieldDataGenerator = info->m_nearFieldDataGenerator;
            auto item = info->m_sidebarItem;
            auto sideBarSettingData = info->m_SEFMSidebarData;
            if (sideBarSettingData != nullptr)//取对数 db
            {
                if (sliderBarSettingData != nullptr)
                {
                    sliderBarSettingData->setScalarBarIsLog(sideBarSettingData->getIsLog());
                }
            }

            //单位
            auto dataType = info->m_resultType;
            auto unit =getUnit(dataType);
            if (sliderBarSettingData != nullptr)
            {
                sliderBarSettingData->setScalarBarUnit(unit);
            }
        }
    }

    bool SurfaceElectricFieldMapWindow::getHasSameName(const QString& name) const
    {
        auto model = m_sidebarSettings->getCurveNameListWidget()->model();
        for (int row = 0; row < model->rowCount(); ++row)
        {
            QModelIndex index = model->index(row, 0); // 获取模型中的每一行
            QString itemName = model->data(index, Qt::DisplayRole).toString(); // 获取显示角色的数据
            if (itemName == name)
            {
                return true;
            }
        }
        return false;
    }

    SurfaceElectricFieldMapSidebarData* SurfaceElectricFieldMapWindow::getSidebarDataFromNameItem(QListWidgetItem* item)
    {
        for (auto info : m_graphInfoList)
        {
            if (info->m_sidebarItem == item)
            {
                return info->m_SEFMSidebarData;
            }
        }
        return nullptr;
    }

    InfomationGraph3DBasical* SurfaceElectricFieldMapWindow::getGraph3DInfoFromSidebarData(SurfaceElectricFieldMapSidebarData* data)
    {
        for (auto info : m_graphInfoList)
        {
            if (info->m_SEFMSidebarData == data)
            {
                return info;
            }
        }
        return nullptr;
    }

    void SurfaceElectricFieldMapWindow::updateGeometryActors(bool isShow, bool& hasAnyGeometrySuccess)
    {
        bool _hasAnyGeometry = false;
        m_isShowingGeometry = isShow;
        QList<QStringList> m_updatedList;

        for (auto info : m_graphInfoList)
        {
            const auto& path = info->m_geometryFileName;
            if (path.empty())
            {
                continue;
            }

            //auto isAdded = info->m_isGeomtryActorImported;
            //auto geometryActor = info->m_geometryActor;
            if (isShow)
            {
                if (m_updatedList.contains(path))
                {
                    continue;
                }

                //if (info->m_geomtryActorGenerator == nullptr)
                //{
                //    GeomtryActorGenerator* generator = new GeomtryActorGenerator(this);
                //    generator->setFileNameList(path);
                //    //generator->setIsActiveClip(m_isActiveClip);
                //    //generator->setClipPlaneNormalDirection(m_planeNormalDirection);
                //    //generator->setClipPlaneOrigin(m_planeOrigin);
                //    //generator->updateActor();
                //    info->m_geomtryActorGenerator = generator;
                //    //info->m_geometryActor = generator->getActor();
                //    m_render3D->AddActor(generator->getActor());
                //}

                m_updatedList.append(path);

                info->m_geomtryActorGenerator->setIsActiveClip(m_isActiveClip);
                info->m_geomtryActorGenerator->setClipPlaneNormalDirection(m_planeNormalDirection);
                info->m_geomtryActorGenerator->setClipPlaneOrigin(m_planeOrigin);
                int status = info->m_geomtryActorGenerator->updateActor();
                if (status == 2)//全部失败的情况
                {
                    //QString _errorText = info->m_geomtryActorGenerator->getErrorMessage();
                    //emit IBaseSignalInstance->signal_sendErrorMessageToUI(_errorText);
                    //delete info->m_geomtryActorGenerator;
                    //info->m_geomtryActorGenerator = nullptr;
                    continue;
                }
                //else if (status == 1)//部分失败的情况，继续执行
                //{
                //    QString _errorText = info->m_geomtryActorGenerator->getErrorMessage();
                //    emit IBaseSignalInstance->signal_sendErrorMessageToUI(_errorText);
                //}
                auto centerSetting = getMainSettingData(info);
                int tranceparency = centerSetting->getGeometrySettingData()->getGeometryTransparency();

                if (tranceparency == 100)//全部透明的情况
                {
                    info->m_geomtryActorGenerator->getActor()->SetVisibility(false);

                }
                else
                {
                    info->m_geomtryActorGenerator->getActor()->SetVisibility(true);
                }

                m_render3D->AddActor(info->m_geomtryActorGenerator->getActor());
                _hasAnyGeometry = true;
            }
            else
            {
                if (info->m_geomtryActorGenerator != nullptr)
                {
                    info->m_geomtryActorGenerator->getActor()->SetVisibility(0);
                    _hasAnyGeometry = true;
                }
            }
        }

        if (isShow && !_hasAnyGeometry)//全部失败的情况
        {
            emit IBaseSignalInstance->signal_sendErrorMessageToUI("未读取到有效几何文件");
            m_isShowingGeometry = false;//没有几何文件导入成功的情况下，要将显示状态设为false,同时显示模型的按钮设置为未选中
        }
        hasAnyGeometrySuccess = _hasAnyGeometry;

        m_render3D->ResetCameraClippingRange();
        m_renderWindow3D->Render();
    }

    void SurfaceElectricFieldMapWindow::updateMarkerVisibility()
    {
        bool markerState = false;
        int hideCount = 0;
        auto innerMatrkerTable = m_markerDataTable->getInnerTableWidget();
        for (const auto& i : m_marker3DDataInfoList)
        {
            if (m_isActiveClip)
            {
                double* markerPosition = i->m_markerPosition;
                bool isInside = CommonFunction::isPointKeptByPlane(markerPosition[0], markerPosition[1], markerPosition[2],
                    m_planeOrigin[0], m_planeOrigin[1], m_planeOrigin[2], m_planeNormalDirection[0], m_planeNormalDirection[1], m_planeNormalDirection[2]);
                markerState = isInside && i->m_sourceActor->GetVisibility();
            }
            else
            {
                markerState = i->m_sourceActor->GetVisibility();
            }

            // 同步标记actor可见性
            i->m_markerActor->SetVisibility(markerState);
            i->m_markerTextActor->SetVisibility(markerState);

            // 同步markerTable可见性
            for (int row = 0; row < innerMatrkerTable->rowCount(); ++row)
            {
                if (innerMatrkerTable->item(row, 0)->text().toInt() == i->m_markerId)
                {
                    innerMatrkerTable->setRowHidden(row, !markerState);
                    hideCount++;
                }
            }
        }

        // 判断是否全部隐藏，如果是，隐藏标记表格
        bool isAllHide = true;
        for (int row = 0; row < innerMatrkerTable->rowCount(); ++row)
        {
            if (!innerMatrkerTable->isRowHidden(row))
            {
                isAllHide = false;
                break;
            }
        }
        isAllHide ? m_markerDataTable->hide() : m_markerDataTable->show();
    }

    void SurfaceElectricFieldMapWindow::slot_addCustomContextMenu(const QPoint& pos)
    {
        QMenu contextMenu(this);

        // 添加主菜单项
        if (!m_isAddingCellMarker && !m_isAddingPointMarker)
        {
            for (auto i : m_graphInfoList)
            {
                if (i->m_currentScalarArray.arrayIndex != -1)//表面场只有一个数据，并且
                {
                    if (i->m_currentScalarArray.type == FieldGraphGenerator::StructureType::POINTS)
                    {
                        //QMenu* addMarkerMenu = contextMenu.addMenu("添加标记");
                        QAction* addPointMarker = contextMenu.addAction("添加点标记");
                        QObject::connect(addPointMarker, &QAction::triggered, this, &Graph3DWindowBase::slot_beginAddPointMarker);
                    }
                    else if (i->m_currentScalarArray.type == FieldGraphGenerator::StructureType::CELLS)
                    {
                        //QMenu* addMarkerMenu = contextMenu.addMenu("添加标记");
                        QAction* addCellMarker = contextMenu.addAction("添加面标记");
                        QObject::connect(addCellMarker, &QAction::triggered, this, &Graph3DWindowBase::slot_beginAddCellMarker);
                    }
                    break;
                }
            }
        }
        if (m_isAddingCellMarker || m_isAddingPointMarker)
        {
            QAction* stopAddMarkerMenu = contextMenu.addAction("退出标记模式");
            QObject::connect(stopAddMarkerMenu, &QAction::triggered, this, &Graph3DWindowBase::slot_stopAddMarker);
        }

        int selectedRowCount = m_markerDataTable->getInnerTableWidget()->selectedItems().size();
        QAction* deleteChosenMarker = contextMenu.addAction("删除选中标记");
        deleteChosenMarker->setEnabled(selectedRowCount > 0);
        int rowCount = m_markerDataTable->getInnerTableWidget()->rowCount();
        QAction* deleteAllMarkers = contextMenu.addAction("删除所有标记");
        deleteAllMarkers->setEnabled(rowCount > 0);
        QAction* exportTableData = contextMenu.addAction("导出标记数据");
        exportTableData->setEnabled(rowCount > 0);

        QObject::connect(deleteChosenMarker, &QAction::triggered, this, &Graph3DWindowBase::slot_removeChosenMarker);
        QObject::connect(deleteAllMarkers, &QAction::triggered, this, &Graph3DWindowBase::slot_removeAllMarker);
        QObject::connect(exportTableData, &QAction::triggered, this, &Graph3DWindowBase::slot_exportTableData);

        contextMenu.exec(m_qvtkWidget->mapToGlobal(pos));
    }


    void SurfaceElectricFieldMapWindow::slot_renameCheck()
    {
        auto listWidget = m_sidebarSettings->getCurveNameListWidget();
        auto selectedItems = listWidget->selectedItems();
        if (selectedItems.size() != 1)
        {
            return;
        }
        auto item = selectedItems[0];
        auto info = getInfoFromSidebarNameItem(item);
        //auto graph = qobject_cast<QCPGraph*>(info->getCurveLineAddress());

        if (item->text().isEmpty())
        {
            EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("命名不能为空，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
            item->setText(info->m_name);
            return;
        }

        for (auto i: m_graphInfoList)
        {
            auto tmpItem = i->m_sidebarItem;
            if (tmpItem == item)
            {
                continue;
            }
            if (item->text() == tmpItem->text())
            {
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("当前名称已存在，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
                item->setText(info->m_name);
                return;
            }
        }
        info->m_isGraphRenamed = true;
        synchronousActorName(info, item->text());

        QStringList _pyCodes{};
        QString newName = "'" + item->text() + "'";
        _pyCodes += QString("surfaceelectricfieldmapsidebarsettings3 = PostProcessing.SurfaceElectricFieldMapSidebarSettingsPy()");
        _pyCodes += QString("surfaceelectricfieldmapsidebarsettings3.nameItemRename(%1,%2,%3)").arg(m_windowId).arg(listWidget->row(item)).arg(newName);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);
    }

    bool SurfaceElectricFieldMapWindow::slot_checkResultNameIsValid(SurfaceElectricFieldMapSettingData* data, const QString& newName)
    {
        if (newName.isEmpty())
        {
            EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("命名不能为空，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
            return false;
        }

        for (auto i : m_graphInfoList)
        {
            if (i->m_surfaceElectricFieldMapSettingData == data)
            {
                continue;
            }
            if (i->m_surfaceElectricFieldMapSettingData->getResultDataSettingData()->getResultDataName() == newName)
            {
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("当前名称已存在，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
                return false;
            }
        }
     
        for (auto i : m_graphInfoList)
        {
            if (i->m_surfaceElectricFieldMapSettingData == data && i->m_name != newName)//是重命名
            {
                i->m_isGraphRenamed = true;
                break;
            }
        }

        return true;
    }

    void SurfaceElectricFieldMapWindow::synchronousActorName(InfomationGraph3DBasical* info, const QString& newName)
    {
        if (info == nullptr)
        {
            return;
        }

        auto item = info->m_sidebarItem;
        if (item == nullptr)
        {
            return;
        }

        QSignalBlocker bl(m_sidebarSettings->getCurveNameListWidget());
        item->setText(newName);
        item->setToolTip(newName);

        info->m_name = newName;

        auto sidebarSetting = info->m_SEFMSidebarData;
        if (sidebarSetting != nullptr)
        {
            sidebarSetting->setGraphName(newName);
            sidebarSetting->setIsGraphNameRenamed(true);
        }

        auto mainSetting = getMainSettingData(info);
        if (mainSetting != nullptr)
        {
            mainSetting->getResultDataSettingData()->setResultDataName(newName);
        }
    }
} // namespace pst
